package com.syh.jn.scm.service.impl.supplier.finance;

import cn.redscarf.commons.wrapper.Restrictions;
import cn.redscarf.commons.wrapper.Wrapper;
import com.alibaba.dubbo.config.annotation.Service;
import com.syh.core.ddd.event.annotation.DomainEventHandle;
import com.syh.jn.scm.domain.downstream.entity.finance.DownCostBill;
import com.syh.jn.scm.domain.downstream.entity.finance.DownIncomeBill;
import com.syh.jn.scm.domain.downstream.entity.finance.DownPaymentBill;
import com.syh.jn.scm.domain.downstream.event.DownCostBillEvent;
import com.syh.jn.scm.domain.downstream.event.DownIncomeBillEvent;
import com.syh.jn.scm.domain.downstream.event.DownPaymentBillEvent;
import com.syh.jn.scm.domain.driver.entity.logistics.DriverLogisticsBill;
import com.syh.jn.scm.domain.driver.event.DriverLogisticsBillEvent;
import com.syh.jn.scm.domain.supplier.entity.base.downstream.Downstream;
import com.syh.jn.scm.domain.supplier.entity.base.logistics.Logistics;
import com.syh.jn.scm.domain.supplier.entity.base.upstream.Upstream;
import com.syh.jn.scm.domain.supplier.entity.finance.*;
import com.syh.jn.scm.domain.supplier.entity.logistics.LogisticsBill;
import com.syh.jn.scm.domain.supplier.entity.logistics.LogisticsBillItem;
import com.syh.jn.scm.domain.supplier.event.*;
import com.syh.jn.scm.domain.supplier.event.finance.BusinessAccountRecordEvent;
import com.syh.jn.scm.domain.supplier.event.finance.ReceiptBillEvent;
import com.syh.jn.scm.domain.supplier.repository.finance.*;
import com.syh.jn.scm.domain.supplier.repository.logistics.LogisticsBillRepository;
import com.syh.jn.scm.domain.upstream.entity.finance.UpCostBill;
import com.syh.jn.scm.domain.upstream.entity.finance.UpIncomeBill;
import com.syh.jn.scm.domain.upstream.entity.finance.UpReceiptBill;
import com.syh.jn.scm.domain.upstream.event.UpCostBillEvent;
import com.syh.jn.scm.domain.upstream.event.UpIncomeBillEvent;
import com.syh.jn.scm.domain.upstream.event.UpReceiptBillEvent;
import com.syh.jn.scm.dto.supplier.finance.BusinessAccountSummaryVo;
import com.syh.jn.scm.exception.BusinessException;
import com.syh.jn.scm.service.api.downstream.finance.enums.DownCostBillEnum;
import com.syh.jn.scm.service.api.supplier.finance.BusinessAccountSummaryService;
import com.syh.jn.scm.service.api.supplier.finance.enums.BusinessAccountRecordEnums;
import com.syh.jn.scm.service.api.supplier.finance.enums.BusinessAccountSummaryEnums;
import com.syh.jn.scm.service.api.supplier.support.enums.SupplierEnums;
import com.syh.jn.scm.service.api.upstream.finance.enums.UpCostBillEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * 单位应收付记录汇总表
 */
@Service
@Transactional
public class BusinessAccountSummaryServiceImpl implements BusinessAccountSummaryService {
  @Autowired
  private BusinessAccountSummaryRepository businessAccountSummaryRepository;
  @Autowired
  private LogisticsBillRepository logisticsBillRepository;
  @Autowired
  private CostBillRepository costBillRepository;
  @Autowired
  private IncomeBillRepository incomeBillRepository;
  @Autowired
  private PaymentBillRepository paymentBillRepository;
  @Autowired
  private ReceiptBillRepository receiptBillRepository;

//  /**
//   * 费用单双方确认
//   * @param bill
//   */
//  @DomainEventHandle(CostBillEvent.COST_BILL_STATE_CONFIRM)
//  protected void handleCostBillConfirmEvent(CostBill bill) {
//    //查找所属公司的应收付数据
//    BusinessAccountSummary summary = this.findBusinessAccountSummary(bill.getBusinessEntityId(), Short.valueOf(bill.getCustomerType().toString()), bill.getCustomerId());
//    //更新应付金额
//    if (bill.getCustomerType() != null
//            && bill.getCustomerType().equals(SupplierEnums.AccountType.UPSTREAM.getStatus())) {
//      summary.setPaymentTotalAmount(summary.getPaymentTotalAmount().add(bill.getPrice()));
//    } else {
//      summary.setReceiveTotalAmount(summary.getReceiveTotalAmount().subtract(bill.getPrice()));
//    }
//    businessAccountSummaryRepository.update(summary);
//  }
//
//  /**
//   * 下游收入单双方确认
//   * @param bill
//   */
//  @DomainEventHandle(DownIncomeBillEvent.DOWNSTREAM_INCOME_BILL_STATE_CONFIRM)
//  protected void handleDownIncomeBillConfirmEvent(DownIncomeBill bill) {
//    CostBill costBill = costBillRepository.getById(bill.getId());
//    this.handleCostBillConfirmEvent(costBill);
//  }
//
//  /**
//   * 上游收入单双方确认
//   * @param bill
//   */
//  @DomainEventHandle(UpIncomeBillEvent.UP_INCOME_BILL_STATE_CONFIRM)
//  protected void handleUpIncomeBillConfirmEvent(UpIncomeBill bill) {
//    CostBill costBill = costBillRepository.getById(bill.getId());
//    this.handleCostBillConfirmEvent(costBill);
//  }
//
//  /**
//   * 服务商费用单取消确认
//   * @param bill
//   */
//  @DomainEventHandle(CostBillEvent.COST_BILL_STATE_UN_CONFIRM)
//  protected void handleCostBillUnConfirmEvent(CostBill bill) {
//    //查找所属公司的应收付数据
//    BusinessAccountSummary summary = this.findBusinessAccountSummary(bill.getBusinessEntityId(), Short.valueOf(bill.getCustomerType().toString()), bill.getCustomerId());
//    if (bill.getCustomerType() != null
//            && bill.getCustomerType().equals(SupplierEnums.AccountType.UPSTREAM.getStatus())) {
//      summary.setPaymentTotalAmount(summary.getPaymentTotalAmount().subtract(bill.getPrice()));
//    } else {
//      summary.setReceiveTotalAmount(summary.getReceiveTotalAmount().add(bill.getPrice()));
//    }
//    businessAccountSummaryRepository.update(summary);
//  }
//
//  /**
//   * 下游收入单取消确认
//   * @param bill
//   */
//  @DomainEventHandle(DownIncomeBillEvent.DOWNSTREAM_INCOME_BILL_STATE_UN_CONFIRM)
//  protected void handleDownIncomeBillUnConfirmEvent(DownIncomeBill bill) {
//    CostBill costBill = costBillRepository.getById(bill.getId());
//    this.handleCostBillUnConfirmEvent(costBill);
//  }
//
//  /**
//   * 上游收入单取消确认
//   * @param bill
//   */
//  @DomainEventHandle(UpIncomeBillEvent.UP_INCOME_BILL_STATE_UN_CONFIRM)
//  protected void handleUpIncomeBillRemoveEvent(UpIncomeBill bill) {
//    CostBill costBill = costBillRepository.getById(bill.getId());
//    this.handleCostBillUnConfirmEvent(costBill);
//  }
//
//  /**
//   * 服务商收入单双方确认
//   * @param bill
//   */
//  @DomainEventHandle(IncomeBillEvent.INCOME_BILL_STATE_CONFIRM)
//  protected void handleIncomeBillConfirmEvent(IncomeBill bill) {
//    //查找所属公司的应收付数据
//    BusinessAccountSummary summary = this.findBusinessAccountSummary(bill.getBusinessEntityId(), bill.getCustomerType(), bill.getCustomerId());
//    if (bill.getCustomerType() != null
//            && bill.getCustomerType().equals(SupplierEnums.AccountType.UPSTREAM.getStatus())) {
//      summary.setPaymentTotalAmount(summary.getPaymentTotalAmount().subtract(bill.getPrice()));
//    } else {
//      summary.setReceiveTotalAmount(summary.getReceiveTotalAmount().add(bill.getPrice()));
//    }
//    businessAccountSummaryRepository.update(summary);
//  }
//
//  /**
//   * 下游费用单双方确认
//   * @param bill
//   */
//  @DomainEventHandle(DownCostBillEvent.DOWNSTREAM_COST_BILL_STATE_CONFIRM)
//  protected void handleDownCostBillConfirmEvent(DownCostBill bill) {
//    IncomeBill incomeBill = incomeBillRepository.getById(bill.getId());
//    this.handleIncomeBillConfirmEvent(incomeBill);
//  }
//
//  /**
//   * 上游费用单双方确认
//   * @param bill
//   */
//  @DomainEventHandle(UpCostBillEvent.UP_COST_BILL_STATE_CONFIRM)
//  protected void handleUpCostBillConfirmEvent(UpCostBill bill) {
//    IncomeBill incomeBill = incomeBillRepository.getById(bill.getId());
//    this.handleIncomeBillConfirmEvent(incomeBill);
//  }
//
//  /**
//   * 服务商收入单据取消确认
//   * @param bill
//   */
//  @DomainEventHandle(IncomeBillEvent.INCOME_BILL_STATE_UN_CONFIRM)
//  protected void handleIncomeBillUnConfirmEvent(IncomeBill bill) {
//    //查找所属公司的应收付数据
//    BusinessAccountSummary summary = this.findBusinessAccountSummary(bill.getBusinessEntityId(), bill.getCustomerType(), bill.getCustomerId());
//    if (bill.getCustomerType() != null
//            && bill.getCustomerType().equals(SupplierEnums.AccountType.UPSTREAM.getStatus())) {
//      summary.setPaymentTotalAmount(summary.getPaymentTotalAmount().add(bill.getPrice()));
//    } else {
//      summary.setReceiveTotalAmount(summary.getReceiveTotalAmount().subtract(bill.getPrice()));
//    }
//    businessAccountSummaryRepository.update(summary);
//  }
//
//  /**
//   * 下游费用单取消确认
//   * @param bill
//   */
//  @DomainEventHandle(DownCostBillEvent.DOWNSTREAM_COST_BILL_UN_CONFIRM)
//  protected void handleDownCostBillUnConfirmEvent(DownCostBill bill) {
//    IncomeBill incomeBill = incomeBillRepository.getById(bill.getId());
//    this.handleIncomeBillUnConfirmEvent(incomeBill);
//  }
//
//  /**
//   * 上游费用单取消确认
//   * @param bill
//   */
//  @DomainEventHandle(UpCostBillEvent.UP_COST_BILL_STATE_UN_CONFIRM)
//  protected void handleUpCostBillUnConfirmEvent(UpCostBill bill) {
//    IncomeBill incomeBill = incomeBillRepository.getById(bill.getId());
//    this.handleIncomeBillUnConfirmEvent(incomeBill);
//  }
//
//  /**
//   * 服务商付款单据锁定（双方确认）
//   * @param bill
//   */
//  @DomainEventHandle(PaymentBillEvent.PAYMENT_BILL_LOCK)
//  protected void handlePaymentBillLockEvent(PaymentBill bill) {
//    //查找所属公司的应收付数据
//    BusinessAccountSummary summary = this.findBusinessAccountSummary(bill.getBusinessEntityId(), bill.getCustomerType(), bill.getCustomerId());
//    summary.setPaymentAmount(summary.getPaymentAmount().add(bill.getPrice()));
//    businessAccountSummaryRepository.update(summary);
//  }
//
//  /**
//   * 上游收款单（服务商付款单）锁定
//   * @param receiptBill
//   */
//  @DomainEventHandle(UpReceiptBillEvent.UP_RECEIPT_BILL_LOCK)
//  protected void handleUpReceiptBillLockEvent(UpReceiptBill receiptBill) {
//    PaymentBill paymentBill = paymentBillRepository.getById(receiptBill.getId());
//    this.handlePaymentBillLockEvent(paymentBill);
//  }
//
//  /**
//   * 服务商付款单据取消锁定
//   * @param bill
//   */
//  @DomainEventHandle(PaymentBillEvent.PAYMENT_BILL_UNLOCK)
//  protected void handlePaymentBillUnLockEvent(PaymentBill bill) {
//    //查找所属公司的应收付数据
//    BusinessAccountSummary summary = this.findBusinessAccountSummary(bill.getBusinessEntityId(), bill.getCustomerType(), bill.getCustomerId());
//    summary.setPaymentAmount(summary.getPaymentAmount().subtract(bill.getPrice()));
//    businessAccountSummaryRepository.update(summary);
//  }
//
//  /**
//   * 上游收款单据取消锁定
//   * @param receiptBill
//   */
//  @DomainEventHandle(UpReceiptBillEvent.UP_RECEIPT_BILL_UNLOCK)
//  protected void handleUpReceiptBillUnLockEvent(UpReceiptBill receiptBill) {
//    PaymentBill paymentBill = paymentBillRepository.getById(receiptBill.getId());
//    this.handlePaymentBillUnLockEvent(paymentBill);
//  }
//
//  /**
//   * 服务商收款单据锁定（双方确认）
//   * @param bill
//   */
//  @DomainEventHandle(ReceiptBillEvent.RECEIPT_BILL_LOCK)
//  protected void handleReceiptBillLockEvent(ReceiptBill bill) {
//    //查找所属公司的应收付数据
//    BusinessAccountSummary summary = this.findBusinessAccountSummary(bill.getBusinessEntityId(), bill.getCustomerType(), bill.getCustomerId());
//    summary.setReceiveAmount(summary.getReceiveAmount().add(bill.getPrice()));
//    businessAccountSummaryRepository.update(summary);
//  }
//
//  /**
//   * 下游付款单（服务商收款）单据锁定
//   * @param bill
//   */
//  @DomainEventHandle(DownPaymentBillEvent.DOWN_PAYMENT_BILL_LOCK)
//  protected void handleDownPaymentBillLockEvent(DownPaymentBill bill) {
//    ReceiptBill receiptBill = receiptBillRepository.getById(bill.getId());
//    this.handleReceiptBillLockEvent(receiptBill);
//  }
//
//  /**
//   * 服务商收款单据取消锁定
//   * @param bill
//   */
//  @DomainEventHandle(ReceiptBillEvent.RECEIPT_BILL_UNLOCK)
//  protected void handleReceiptBillUnLockEvent(ReceiptBill bill) {
//    //查找所属公司的应收付数据
//    BusinessAccountSummary summary = this.findBusinessAccountSummary(bill.getBusinessEntityId(), bill.getCustomerType(), bill.getCustomerId());
//    summary.setReceiveAmount(summary.getReceiveAmount().subtract(bill.getPrice()));
//    businessAccountSummaryRepository.update(summary);
//  }
//
//  /**
//   * 下游付款（服务商收款）单据取消锁定
//   * @param bill
//   */
//  @DomainEventHandle(DownPaymentBillEvent.DOWN_PAYMENT_BILL_UNLOCK)
//  protected void handleDownPaymentBillUnLockEvent(DownPaymentBill bill) {
//    ReceiptBill receiptBill = receiptBillRepository.getById(bill.getId());
//    this.handleReceiptBillUnLockEvent(receiptBill);
//  }
//
//  /**
//   * 监听物流单发货
//   * @param bill
//   */
//  @DomainEventHandle(LogisticsBillEvent.LOGISTICS_BILL_DELIVERY)
//  protected void handleLogisticsBillDeliveryEvent(LogisticsBill bill) {
//    switch (bill.getOrderType()) {
//      //销售、采购退货
//      case 0:
//      case 3:
//        bill = logisticsBillRepository.getById(bill.getId());
//        //查找所属公司的应收付数据
//        BusinessAccountSummary summary = this.findBusinessAccountSummary(bill.getBusinessEntityId(), bill.getCustomerType(), bill.getCustomerId());
//        //计算物流单据商品总额
//        BigDecimal billTotalAmount = BigDecimal.ZERO;
//        for (LogisticsBillItem item : bill.getItems()) {
//          billTotalAmount = billTotalAmount.add(item.getPrice().multiply(item.getQuantity()).setScale(2, BigDecimal.ROUND_HALF_UP));
//        }
//        billTotalAmount = summary.getReceiveTotalAmount().add(billTotalAmount);
//        summary.setReceiveTotalAmount(billTotalAmount);
//        //更新应付金额
//        businessAccountSummaryRepository.update(summary);
//        break;
//      //采购、销售退货不处理
//      case 1:
//      case 2:
//        break;
//      default:
//        throw new BusinessException("订单类型错误！");
//    }
//  }
//
//  /**
//   * 监听司机端物流单发货
//   *
//   * @param driverLogisticsBill
//   */
//  @DomainEventHandle(DriverLogisticsBillEvent.DRIVER_LOGISTICS_BILL_DELIVERY)
//  protected void handleLogisticsBillDeliveryEvent(DriverLogisticsBill driverLogisticsBill) {
//    LogisticsBill bill = logisticsBillRepository.getById(driverLogisticsBill.getId());
//    this.handleLogisticsBillDeliveryEvent(bill);
//  }
//
//  /**
//   * 监听物流单收货
//   *
//   * @param bill
//   */
//  @DomainEventHandle(LogisticsBillEvent.LOGISTICS_BILL_COLLECTED)
//  protected void handleLogisticsBillCollectedEvent(LogisticsBill bill) {
//    switch (bill.getOrderType()) {
//      //采购退货、销售不处理
//      case 0:
//      case 3:
//        break;
//      //销售退货、采购
//      case 1:
//      case 2:
//        bill = logisticsBillRepository.getById(bill.getId());
//        //查找所属公司的应收付数据
//        BusinessAccountSummary summary = this.findBusinessAccountSummary(bill.getBusinessEntityId(), bill.getCustomerType(), bill.getCustomerId());
//        //计算物流单据商品总额
//        BigDecimal billTotalAmount = BigDecimal.ZERO;
//        for (LogisticsBillItem item : bill.getItems()) {
//          billTotalAmount = billTotalAmount.add(item.getPrice().multiply(item.getQuantity()).setScale(2, BigDecimal.ROUND_HALF_UP));
//        }
//        billTotalAmount = summary.getPaymentTotalAmount().add(billTotalAmount);
//        summary.setPaymentTotalAmount(billTotalAmount);
//        //更新应付金额
//        businessAccountSummaryRepository.update(summary);
//        break;
//      default:
//        throw new BusinessException("订单类型错误！");
//    }
//  }
//
//  /**
//   * 监听司机端物流单收货
//   *
//   * @param driverLogisticsBill
//   */
//  @DomainEventHandle(DriverLogisticsBillEvent.DRIVER_LOGISTICS_BILL_COLLECTED)
//  protected void handleLogisticsBillCollectedEvent(DriverLogisticsBill driverLogisticsBill) {
//    LogisticsBill bill = logisticsBillRepository.getById(driverLogisticsBill.getId());
//    this.handleLogisticsBillCollectedEvent(bill);
//  }
//
//  /**
//   * 监听物流单取消签收
//   *
//   * @param bill
//   */
//  @DomainEventHandle(LogisticsBillEvent.LOGISTICS_BILL_UN_RECEIVED)
//  protected void handleLogisticsBillUnReceivedEvent(LogisticsBill bill) {
//
//    bill = logisticsBillRepository.getById(bill.getId());
//    //查找所属公司的应收付数据
//    BusinessAccountSummary summary = this.findBusinessAccountSummary(bill.getBusinessEntityId(), bill.getCustomerType(), bill.getCustomerId());
//    //计算物流单据商品总额
//    BigDecimal billTotalAmount = BigDecimal.ZERO;
//
//    for (LogisticsBillItem item : bill.getItems()) {
//      billTotalAmount = billTotalAmount.add(item.getPrice().multiply(item.getQuantity()).setScale(2, BigDecimal.ROUND_HALF_UP));
//    }
//    switch (bill.getOrderType()) {
//      //销售退货、采购
//      case 1:
//      case 2:
//        billTotalAmount = summary.getPaymentTotalAmount().subtract(billTotalAmount);
//        summary.setPaymentTotalAmount(billTotalAmount);
//        break;
//      default:
//        throw new BusinessException("订单类型错误！");
//    }
//    //更新应付金额
//    businessAccountSummaryRepository.update(summary);
//  }
//
//  /**
//   * 监听物流单修改事件
//   *
//   * @param bill
//   */
//  @DomainEventHandle({LogisticsBillEvent.LOGISTICS_BILL_UPDATED})
//  protected void handleLogisticsBillUpdateEvent(LogisticsBill oldBill, LogisticsBill bill) {
//    if (oldBill.getBusinessEntityId().equals(bill.getBusinessEntityId())
//            || oldBill.getCustomerType().equals(bill.getCustomerType()) || oldBill.getCustomerId().equals(bill.getCustomerId())) {
//      throw new BusinessException("物流单据不能修改归属人！");
//    }
//
//    //查找所属公司的应收付数据
//    BusinessAccountSummary summary = this.findBusinessAccountSummary(oldBill.getBusinessEntityId(), oldBill.getCustomerType(), oldBill.getCustomerId());
//    //计算物流单据商品总额
//    BigDecimal oldBillTotalAmount = BigDecimal.ZERO;
//    BigDecimal billTotalAmount = BigDecimal.ZERO;
//    for (LogisticsBillItem item : oldBill.getItems()) {
//      oldBillTotalAmount = oldBillTotalAmount.add(item.getPrice().multiply(item.getQuantity()).setScale(2, BigDecimal.ROUND_HALF_UP));
//    }
//    for (LogisticsBillItem item : bill.getItems()) {
//      billTotalAmount = billTotalAmount.add(item.getPrice().multiply(item.getQuantity()).setScale(2, BigDecimal.ROUND_HALF_UP));
//    }
//    switch (bill.getOrderType()) {
//      //销售、采购退货
//      case 0:
//      case 3:
//        summary.setReceiveTotalAmount(summary.getReceiveTotalAmount().subtract(oldBillTotalAmount));
//        summary.setReceiveTotalAmount(summary.getReceiveTotalAmount().add(billTotalAmount));
//        break;
//      //销售退货、采购
//      case 1:
//      case 2:
//        summary.setPaymentTotalAmount(summary.getPaymentTotalAmount().subtract(oldBillTotalAmount));
//        summary.setPaymentTotalAmount(summary.getPaymentTotalAmount().add(billTotalAmount));
//        break;
//      default:
//        throw new BusinessException("订单类型错误！");
//    }
//    //更新应付金额
//    businessAccountSummaryRepository.update(summary);
//  }
//
//  /**
//   * 监听物流单取消发货
//   *
//   * @param bill
//   */
//  @DomainEventHandle({LogisticsBillEvent.LOGISTICS_BILL_CANCELLED})
//  protected void handleLogisticsBillCancelEvent(LogisticsBill bill) {
//
//    bill = logisticsBillRepository.getById(bill.getId());
//    //查找所属公司的应收付数据
//    BusinessAccountSummary summary = this.findBusinessAccountSummary(bill.getBusinessEntityId(), bill.getCustomerType(), bill.getCustomerId());
//    //计算物流单据商品总额
//    BigDecimal billTotalAmount = BigDecimal.ZERO;
//    for (LogisticsBillItem item : bill.getItems()) {
//      billTotalAmount = billTotalAmount.add(item.getPrice().multiply(item.getQuantity()).setScale(2, BigDecimal.ROUND_HALF_UP));
//    }
//    switch (bill.getOrderType()) {
//      //销售、采购退货
//      case 0:
//      case 3:
//        billTotalAmount = summary.getReceiveTotalAmount().subtract(billTotalAmount);
//        summary.setReceiveTotalAmount(billTotalAmount);
//        break;
//      default:
//        throw new BusinessException("订单类型错误！");
//    }
//    //更新应付金额
//    businessAccountSummaryRepository.update(summary);
//  }
//
  /**
   * 消费者：监听下游客户新增信息
   *
   * @param downstream
   */
  @DomainEventHandle(DownstreamEvent.DOWNSTREAM_CREATED)
  protected void handleDownstreamCreatedEvent(Downstream downstream) {
    BusinessAccountSummary businessAccountSummary = new BusinessAccountSummary(downstream);
    businessAccountSummaryRepository.add(businessAccountSummary);
  }

  /**
   * 消费者：监听上游供应商新增信息
   *
   * @param upstream
   */
  @DomainEventHandle(UpstreamEvent.UPSTREAM_CREATED)
  protected void handleUpstreamCreatedEvent(Upstream upstream) {
    BusinessAccountSummary businessAccountSummary = new BusinessAccountSummary(upstream);
    businessAccountSummaryRepository.add(businessAccountSummary);
  }

  /**
   * 消费者：监听物流客户新增信息
   *
   * @param logistics
   */
  @DomainEventHandle(LogisticsEvent.LOGISTICS_CREATED)
  protected void handleLogisticsCreatedEvent(Logistics logistics) {
    BusinessAccountSummary businessAccountSummary = new BusinessAccountSummary(logistics);
    businessAccountSummaryRepository.add(businessAccountSummary);
  }

  /**
   * 消费者：监听往来单位删除信息
   * @param obj
   */
  @DomainEventHandle({UpstreamEvent.UPSTREAM_DELETED,DownstreamEvent.DOWNSTREAM_DELETED,LogisticsEvent.LOGISTICS_DELETED})
  protected void handleCompanyDeletedEvent(Object obj) {
    Wrapper we = Wrapper.build();
    if(obj.getClass() == Upstream.class){
      we.append(Restrictions.eq("businessEntityId",((Upstream) obj).getBusinessEntityId()));
      we.append(Restrictions.eq("customerType", BusinessAccountSummaryEnums.CustomerType.UPSTREAM.getStatus()));
      we.append(Restrictions.eq("customerId",((Upstream) obj).getId()));
    }
    else if(obj.getClass() == Downstream.class){
      we.append(Restrictions.eq("businessEntityId",((Downstream) obj).getBusinessEntityId()));
      we.append(Restrictions.eq("customerType", BusinessAccountSummaryEnums.CustomerType.DOWNSTREAM.getStatus()));
      we.append(Restrictions.eq("customerId",((Downstream) obj).getId()));
    }
    else if(obj.getClass() == Logistics.class){
      we.append(Restrictions.eq("businessEntityId",((Logistics) obj).getBusinessEntityId()));
      we.append(Restrictions.eq("customerType", BusinessAccountSummaryEnums.CustomerType.LOGISTICS.getStatus()));
      we.append(Restrictions.eq("customerId",((Logistics) obj).getId()));
    }
    BusinessAccountSummary entity = businessAccountSummaryRepository.getOne(we);
    businessAccountSummaryRepository.remove(entity);
  }

  /**
   * 消费者：监听应收付记录新增
   * @param businessAccountRecord
   */
  @DomainEventHandle(BusinessAccountRecordEvent.BUSINESS_ACCOUNT_RECORD_CREATED)
  protected void handelBusinessAccountRecordCreated(BusinessAccountRecord businessAccountRecord) {
    BusinessAccountSummary businessAccountSummary = this.findBusinessAccountSummary(businessAccountRecord.getBusinessEntityId(), businessAccountRecord.getCustomerType(),businessAccountRecord.getCustomerId());
    businessAccountSummary.updateBusinessAccountSummary(businessAccountRecord);
    businessAccountSummaryRepository.update(businessAccountSummary);
  }

  /**
   * 根据businessEntityId和customerType查找应收付汇总信息
   *
   * @param businessEntityId
   * @param customerType
   * @return
   */
  private BusinessAccountSummary findBusinessAccountSummary(Long businessEntityId, Short customerType, Long customerId) {
    //查找出当前服务商的应收付汇总信息
    Wrapper we = Wrapper.build();
    we.append(Restrictions.eq("businessEntityId", businessEntityId));
    we.append(Restrictions.eq("customerType", customerType));
    we.append(Restrictions.eq("customerId", customerId));
    return businessAccountSummaryRepository.getOne(we);
  }

  @Override
  public List<BusinessAccountSummaryVo> findListPage(Wrapper wrapper, Integer startRow, Integer count) {
    return businessAccountSummaryRepository.findListPageView(wrapper, startRow, count);
  }

  @Override
  public int getCount(Wrapper wrapper) {
    return this.businessAccountSummaryRepository.getCount(wrapper);
  }
}
